package org.example.kafkastudy.config;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.utils.Utils;

import java.util.Map;
import java.util.Random;

public class MyPartitioner implements Partitioner {
    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        if (keyBytes != null) {
            // 如果传了 key，则对 key 进行 hash、取模
            return Utils.toPositive(Utils.murmur2(keyBytes)) % cluster.availablePartitionsForTopic(topic).size();
        }

        // 如果没传 key，则以随机的形式，往前一半 Partition 中转发
        Random rand = new Random();
        int halfOfPartitionSize = cluster.availablePartitionsForTopic(topic).size() / 2; // 本例中 5 / 2 = 2
        int randomNum = rand.nextInt(halfOfPartitionSize); // rand.next(2) 表示获取 0 ~ 1 的随机数

        return randomNum;
    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> configs) {

    }
}
